package cn.stylefeng.guns.utils.weixin;

import cn.hutool.core.io.FileUtil;
import cn.stylefeng.guns.base.consts.ConstantsContext;
import cn.stylefeng.guns.sys.core.exception.enums.BizExceptionEnum;
import cn.stylefeng.guns.sys.modular.system.entity.FileInfo;
import cn.stylefeng.guns.sys.modular.system.model.UploadResult;
import cn.stylefeng.guns.sys.modular.system.service.FileInfoService;
import cn.stylefeng.guns.utils.HttpClientUtil;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import cn.stylefeng.roses.kernel.model.response.ResponseData;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
 
public class WeiXinUtil {
    @Autowired
    private FileInfoService fileInfoService;
    /*
     * 获取公众号的token
     * */
    public static String getToken(){
        String re = "";
        try{
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + WeiXinConfig.sAppID + "&secret=" + WeiXinConfig.secret;
            re = HttpClientUtil.doGet(url);
            WeiXinToken token = JSON.parseObject(re, WeiXinToken.class);
            System.out.println(re);
            if(token != null){
                return token.getAccess_token();
            }
        }catch (Exception e){

        }

        return "";
    }


    public static String getOfficeToken(){
        String re = "";
        try{
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + WeiXinConfig.officeAppID + "&secret=" + WeiXinConfig.officeSecret;
            re = HttpClientUtil.doGet(url);
            WeiXinToken token = JSON.parseObject(re, WeiXinToken.class);
            System.out.println(re);
            if(token != null){
                return token.getAccess_token();
            }
        }catch (Exception e){

        }

        return "";
    }

    public static String getQrCode(String accessToken,String par,String path){
        RestTemplate rest = new RestTemplate();
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
            Map<String, Object> param = new HashMap<>();
            param.put("scene", par);
            param.put("page", "pages/index/index");
            param.put("width", 430);
            param.put("auto_color", false);
            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            HttpEntity requestEntity = new HttpEntity(param, headers);
            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class,
                    new Object[0]);
            System.out.println("调用小程序生成微信永久小程序码URL接口返回结果:" + entity.getBody());
            byte[] result = entity.getBody();

            BASE64Encoder base64Encoder=new BASE64Encoder();
            String encodedStr=base64Encoder.encode(result);
                        System.out.println("encodedStr:"+encodedStr);

//            inputStream = new ByteArrayInputStream(result);
//            File file = new File(path);
//            if (!file.exists()) {
//                try {
//                    file.createNewFile();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//            outputStream = new FileOutputStream(file);
//
//
//            int len = 0;
//            byte[] in_b  = null;
//            byte[] buf = new byte[1024];
//            while ((len = inputStream.read(buf, 0, 1024)) != -1) {
//                outputStream.write(buf, 0, len);
//            }
//            outputStream.flush();


              return encodedStr;
        } catch (Exception e) {
            System.out.println("调用异常");
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }
        return null;
    }

    public static Jscode2Session getJsCodeSession(String cd){
        Jscode2Session Tken = null;
        try{
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+WeiXinConfig.sAppID+"&secret="+WeiXinConfig.secret+"&js_code="+cd+"&grant_type=authorization_code";
            String restr = HttpClientUtil.doGet(url);
            Tken = JSON.parseObject(restr, Jscode2Session.class);
        }catch (Exception e){

        }
        return Tken;
    }


    /**
     * 获取用户在公众号的Unionid
     *
     * @throws Exception
     */

    public static Map<String,String> getOfficeUnionid(String code) throws Exception {

//        if (StringUtils.isEmpty(code)){
//            return ReturnT.getFailReturnT("code为空","");
//
//        }
        Map<String,String> map=new HashMap<>();
        String token=getOfficeToken();
        AccessToken ret=GetAccess_Token(code);
        String openid=ret.getOpenid();
        System.out.println("token:"+token);
        System.out.println("openid:"+openid);

        // String url="https://api.weixin.qq.com/sns/userinfo?access_token="+token+"&openid="+openid+"&lang=zh_CN";
        String url="https://api.weixin.qq.com/cgi-bin/user/info?access_token="+token+"&openid="+openid;

        //+"&lang=zh_CN"

        HttpClient hc = new HttpClient(url);
        hc.setHttps(true);//设置https协议
        hc.get();
        String result = hc.getContent();
        JSONObject json = JSONObject.parseObject(result);
        if (json.containsKey("unionid")) {
            map.put("unionid",json.getString("unionid"));
            map.put("openid",openid);
            return   map;
        } else {
            map.put("err","获取公众号unionid失败");
            return map;

        }

    }

    /*
     * 获取授权信息
     * */
    public static AccessToken GetAccess_Token(String cd){
        AccessToken Tken = null;
        try{
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WeiXinConfig.officeAppID + "&secret=" + WeiXinConfig.officeSecret + "&code=" + cd + "&grant_type=authorization_code";
            String restr = HttpClientUtil.doGet(url);
            Tken = JSON.parseObject(restr, AccessToken.class);
        }catch (Exception e){

        }
        return Tken;
    }

    public static WXUserInfo GetUserinfo(AccessToken token){
        WXUserInfo uinfo = null;
        try {
            String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + token.getAccess_token() + "&openid=" + token.getOpenid() + "&lang=zh_CN";

            ////1，基础接口的token 获取接口是
            ////https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
            ////  2，用户网页授权access_token 获取接口地址是
            ////  https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

            //这个获取用户更详细的接口中的access_token是基础接口的token不是用户网页授权access_token, http://www.cnblogs.com/sxmny/articles/4969119.html
            //string url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + token.access_token + "&openid=" + token.openid + "&lang=zh_CN";

            String restr = HttpClientUtil.doGet(url);
            //Response.Write(restr);
            System.out.println("test"+restr);
            uinfo = JSON.parseObject(restr, WXUserInfo.class);

        } catch (Exception ex) {

        }
        return uinfo;
    }

    /// <summary>
    /// 用户登录
    /// </summary>
    /// <param name="code"></param>
    /// <returns></returns>
    public static WeiXinProInfo getProInfo(String code) {
        try {
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + WeiXinConfig.sAppID + "&secret=" + WeiXinConfig.secret + "&js_code=" + code + "&grant_type=authorization_code";
            String re = HttpClientUtil.doGet(url);
            WeiXinProInfo info = JSON.parseObject(re, WeiXinProInfo.class);
            return info;
        }
        catch (Exception e) {
            return null;
        }
    }

    public static WxPhoneData phones(String sessionKey,String iv,String encryptedData){
        System.out.println("key:"+sessionKey);
        String result = AESUtil.decrypt(sessionKey,iv,encryptedData);
        return JSON.parseObject(result, WxPhoneData.class);
    }

    /**
     * 上传文件（指定上传路径）
     *
     * @author fengshuonan
     * @Date 2019-05-04 17:18
     */
    public static UploadResult uploadFile(MultipartFile file, String fileSavePath) {

        UploadResult uploadResult = new UploadResult();

        //生成文件的唯一id
        String fileId = IdWorker.getIdStr();
        uploadResult.setFileId(fileId);

        //获取文件后缀
        String fileSuffix = ToolUtil.getFileSuffix(file.getOriginalFilename());
        uploadResult.setFileSuffix(fileSuffix);

        //获取文件原始名称
        String originalFilename = file.getOriginalFilename();
        uploadResult.setOriginalFilename(originalFilename);

        //生成文件的最终名称
        String finalName = fileId + "." + ToolUtil.getFileSuffix(originalFilename);
        uploadResult.setFinalName(finalName);
        uploadResult.setFileSavePath(fileSavePath + finalName);

        try {
            //保存文件到指定目录
            File newFile = new File(fileSavePath + finalName);

            //创建父目录
            FileUtil.mkParentDirs(newFile);

            //保存文件
            file.transferTo(newFile);

            //保存文件信息
//            FileInfo fileInfo = new FileInfo();
//            fileInfo.setFileId(fileId);
//            fileInfo.setFileName(originalFilename);
//            fileInfo.setFileSuffix(fileSuffix);
//            fileInfo.setFilePath(fileSavePath + finalName);
//            fileInfo.setFinalName(finalName);

            //计算文件大小kb
//            long kb = new BigDecimal(file.getSize())
//                    .divide(BigDecimal.valueOf(1024))
//                    .setScale(0, BigDecimal.ROUND_HALF_UP).longValue();
//            fileInfo.setFileSizeKb(kb);
//            this.save(fileInfo);
        } catch (Exception e) {

            throw new ServiceException(BizExceptionEnum.UPLOAD_ERROR);
        }

        return uploadResult;
    }
}
